package org.esprit.ocm.server.metier.ec2.impl;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.esprit.ocm.client.rpc.ec2.RegistrationService;
import org.esprit.ocm.dto.impl.AwsCredentialsDto;
import org.esprit.ocm.dto.impl.ServerDto;

import com.xerox.amazonws.ec2.Jec2;

public class RegistrationServiceImpl extends BaseServiceImpl implements RegistrationService {

	/**
	 * Register a new AMI from a bucket on S3
	 * 
	 * @param location
	 *            the location on S3
	 * @return the unique imageId of the newly registered AMI.
	 */
	public String registerImage(String location, ServerDto server, AwsCredentialsDto credentials) {

		// initialize the interface
		Jec2 ec2 = this.initConnection(server, credentials);

		try {

			return ec2.registerImage(location);

		} catch (Exception ex) {
			Logger logger = Logger.getLogger(this.getClass().getName());
			logger.log(Level.SEVERE, "Registering image failed: " + ex.getMessage());

			return null;
		}

	}

	/**
	 * Deregister an AMI Image.
	 * 
	 * @param imageId
	 *            the ID of the image to deregister.
	 * 
	 * @return true if successfull, false else
	 */
	public boolean deregisterImage(String imageId, ServerDto server, AwsCredentialsDto credentials) {

		// initialize the interface
		Jec2 ec2 = this.initConnection(server, credentials);

		try {

			ec2.deregisterImage(imageId);

			return true;

		} catch (Exception ex) {
			Logger logger = Logger.getLogger(this.getClass().getName());
			logger.log(Level.SEVERE, "Deregistering image failed: " + ex.getMessage());

			return false;
		}
	}

}
